//
//  UtilsCommon.m
//  Coin
//
//  Created by 杨洋 on 2018/6/10.
//  Copyright © 2018年 zzg. All rights reserved.
//

#import "UtilsCommon.h"
#import <AVFoundation/AVFoundation.h>

@implementation UtilsCommon

+ (CGFloat)getfileSize:(NSString *)path
{
    BOOL isExists;
    // 文件不存在
    isExists = [[NSFileManager defaultManager] fileExistsAtPath:path];
    if(!isExists)
        return 0;
    NSDictionary *outputFileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil];
    //NSLog (@"file size: %f", (unsigned long long)[outputFileAttributes fileSize]/1024.00 /1024.00);
    return (CGFloat)[outputFileAttributes fileSize]/1024.00 /1024.00;
}

+ (void)compressVideoFileURL:(NSURL*) fileURL completeHanlder:(void(^)(NSURL*)) handler
{
    // 通过文件的 url 获取到这个文件的资源
    AVURLAsset *avAsset = [[AVURLAsset alloc] initWithURL:fileURL options:nil];
    // 用 AVAssetExportSession 这个类来导出资源中的属性
    NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];
    // 压缩视频
    if ([compatiblePresets containsObject:AVAssetExportPresetLowQuality]) { // 导出属性是否包含低分辨率
        // 通过资源（AVURLAsset）来定义 AVAssetExportSession，得到资源属性来重新打包资源 （AVURLAsset, 将某一些属性重新定义
        AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:avAsset presetName:AVAssetExportPresetLowQuality];
        // 设置导出文件的存放路径
        NSString *fileName = [NSString stringWithFormat:@"%f.mp4",[NSDate timeIntervalSinceReferenceDate]];
        NSURL *outURL = [NSURL URLWithString:[NSTemporaryDirectory() stringByAppendingPathComponent:fileName]];
        exportSession.outputURL = outURL;
        // 是否对网络进行优化
        exportSession.shouldOptimizeForNetworkUse = true;
        // 转换成MP4格式
        exportSession.outputFileType = AVFileTypeMPEG4;
        // 开始导出,导出后执行完成的block
        [exportSession exportAsynchronouslyWithCompletionHandler:^{
            // 如果导出的状态为完成
            if ([exportSession status] == AVAssetExportSessionStatusCompleted) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    // 更新一下显示包的大小
                    if(handler){
                        handler(outURL);
                    }
                });
            }
        }];
    }
}

#pragma mark - 隐藏手机号中间四位数字
+ (NSString *) numberSuitScanf:(NSString*)number{
    
    //首先验证是不是手机号码
//    NSString *MOBILE = @"^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|7[06-8])\\\\d{8}$";
//    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
//    BOOL isOk = [regextestmobile evaluateWithObject:number];
    
    if ([number bh_IsValidPhoneNumber]) {//如果是手机号码的话
        NSString *numberString = [number stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
        return numberString;
    }
    return number;
}

+ (NSInteger) random4Number
{
    NSInteger num = arc4random() % 10000;
    return num;
}

+ (UIViewController*)currentViewController{
    //获得当前活动窗口的根视图
    UIViewController* vc = [UIApplication sharedApplication].keyWindow.rootViewController;
    while (1)
    {
        //根据不同的页面切换方式，逐步取得最上层的viewController
        if ([vc isKindOfClass:[UITabBarController class]]) {
            vc = ((UITabBarController*)vc).selectedViewController;
        }
        if ([vc isKindOfClass:[UINavigationController class]]) {
            vc = ((UINavigationController*)vc).visibleViewController;
        }
        if (vc.presentedViewController) {
            vc = vc.presentedViewController;
        }else{
            break;
        }
    }
    return vc;
}

+ (NSString*) stringLanguageFromLanguage:(NSString*) language
{
    if([language hasPrefix:@"zh-Hans"]){
        return @"简体中文";
    }else if([language hasPrefix:@"zh-Han"]){
        return @"繁體中文";
    }else if([language hasPrefix:@"en"]){
        return @"English";
    }
    return nil;
}

+ (CGFloat) heightForString:(NSString *)value font:(UIFont*) font andMaxWidth:(CGFloat) width{
    //获取当前文本的属性
    CGSize strSize = [value boundingRectWithSize:CGSizeMake(width - 16, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:nil].size;
    
    return strSize.height + 16.0;
}

+ (CGFloat) heightForTextView:(UITextView *)textView andWidth:(CGFloat)width
{
    // UITextView 上下左右有8px的边距 计算高度必须减去16px
    CGSize sizeToFit = [textView sizeThatFits:CGSizeMake(width, MAXFLOAT)];
    return sizeToFit.height;
}

+ (UIImage *)creatQRcodeWithUrlstring:(NSString *)urlString imageSize:(CGSize) size{
    
    // 1.实例化二维码滤镜
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    // 2.恢复滤镜的默认属性 (因为滤镜有可能保存上一次的属性)
    [filter setDefaults];
    // 3.将字符串转换成NSdata
    NSData *data  = [urlString dataUsingEncoding:NSUTF8StringEncoding];
    // 4.通过KVO设置滤镜, 传入data, 将来滤镜就知道要通过传入的数据生成二维码
    [filter setValue:data forKey:@"inputMessage"];
    // 5.生成二维码
    CIImage *outputImage = [filter outputImage];
    return [self createNonInterpolatedUIImageFormCIImage:outputImage withSize:size.width];
}

+ (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size
{
       CGRect extent = CGRectIntegral(image.extent);
        CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    
         // 1.创建bitmap;
         size_t width = CGRectGetWidth(extent) * scale;
        size_t height = CGRectGetHeight(extent) * scale;
        CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
        CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
        CIContext *context = [CIContext contextWithOptions:nil];
        CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
         CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
         CGContextScaleCTM(bitmapRef, scale, scale);
         CGContextDrawImage(bitmapRef, extent, bitmapImage);
         // 2.保存bitmap到图片
         CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
         CGContextRelease(bitmapRef);
         CGImageRelease(bitmapImage);
         return [UIImage imageWithCGImage:scaledImage];
}

+ (NSString*) dateFormatWithMilliseconds:(NSTimeInterval) milliseconds
{
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"mm分ss秒"];
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:milliseconds];
    return [df stringFromDate:date];
}

+ (NSString*)HHmmssMilliseconds:(NSInteger) milliseconds
{
    NSInteger h = milliseconds / 3600;
    NSInteger m = milliseconds % 3600 / 60;
    NSInteger s = milliseconds % 3600 % 60 % 60;
    return [NSString stringWithFormat:@"%.2ld时%.2ld分%.2ld秒",(long)h,(long)m,(long)s];
}

+ (NSString*)yyyyMMddHHmmssMilliseconds:(long long) milliseconds
{
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *formatStr = [df stringFromDate:[NSDate dateWithTimeIntervalSince1970:milliseconds]];
    return formatStr;
}

+ (NSTimeInterval) timeIntervalForDateFormat:(NSString*) format date:(NSString*) date
{
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:date];
    return [[df dateFromString:date] timeIntervalSince1970];
}

+ (UIImage*) createImageWithColor:(UIColor*) color
{
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}

@end
